#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include "Log.h"
#include "comm.h"
#include "Initadd.h"

namespace sockedmodule
{

    using namespace LogMudule;
    class Socket;
    using SockPtr = std::shared_ptr<Socket>;
    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual void SocketOrDie() = 0;
        virtual void SetSocketOpt() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual SockPtr Accepter(IntAddr *client) = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual int Fd() = 0;
        virtual void Close() = 0;
        void BuildTcpSocketMethod(int port)
        {
            SocketOrDie();
            SetSocketOpt();
            BindOrDie(port);
            ListenOrDie();
        }
    };
    class TcpSocket : public Socket
    {
    public:
        TcpSocket() : _socket(gdefaultsockfd)
        {
        }
        TcpSocket(int sockfd)
            : _socket(sockfd)
        {
        }
        virtual void SocketOrDie() override
        {
            _socket = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_socket < 0)
            {
                LOG(LogLevel::FATAL) << "socket error";
                exit(1);
            }
            LOG(LogLevel::INFO) << "socket success" << _socket;
        }
        virtual void SetSocketOpt() override
        {
            int opt = 1;
            int n = ::setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            (void)n;
        }
        virtual bool BindOrDie(int port) override
        {
            if (_socket == gdefaultsockfd)
            {
                return false;
            }
            IntAddr addr(port);
            int n = ::bind(_socket, addr.NetAddr(), addr.Netaddrlen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind fail";
                exit(2);
            }
            LOG(LogLevel::DEBUG) << "bind success is " << n;

            return true;
        } //
        virtual bool ListenOrDie() override
        {
            if (_socket == gdefaultsockfd)
            {
                return false;
            }
            int n = ::listen(_socket, gbacklog);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "create listen fail";
                exit(3);
            }
            LOG(LogLevel::INFO) << "create listen socket success is " << n;
            return true;
        }
        virtual SockPtr Accepter(IntAddr *client) override
        {
            if (!client)
            {
                return nullptr;
            }
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsocket = accept(_socket, CONV(&peer), &len);
            if (newsocket < 0)
            {
                LOG(LogLevel::WARNING) << "accept fail";
                return nullptr;
            }
            client->SetAddr(peer, len);

            return std::make_shared<TcpSocket>(newsocket);
        }
        virtual void Close() override
        {
            if (_socket == gdefaultsockfd)
            {
                return;
            }
            ::close(_socket);
        }
        virtual ~TcpSocket()
        {
        }
        virtual int Recv(std::string *out) override
        {
            char buffer[1024 * 8];
            auto size = ::recv(_socket, buffer, sizeof(buffer) - 1, 0);
            if (size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }
            return size;
        }
        virtual int Send(const std::string &in) override
        {
            auto size = ::send(_socket, in.c_str(), in.size(), 0);
            return size;
        }
        virtual int Fd() override
        {
            return _socket;
        }

    private:
        int _socket;
    };

}
